package cn.jiadakeji.parent.common.interceptor;

import cn.hutool.core.util.IdUtil;
import io.netty.util.concurrent.FastThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hhaoyu
 * 接口时间花费监控
 */
@Component
public class LogInterceptor implements HandlerInterceptor {
    protected final Logger logger = LoggerFactory.getLogger(" api and time used ");
    private static final FastThreadLocal<Long> startTimeThreadLocal =
            new FastThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();
        MDC.put("requestId", IdUtil.fastSimpleUUID());
        startTimeThreadLocal.set(beginTime);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        try {
            String uri =  request.getRequestURI();
            long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）
            long endTime = System.currentTimeMillis(); 	//2、结束时间
            logger.info(uri+" 耗时： "+ (endTime - beginTime)+"ms");

        }finally {
            MDC.clear();
        }
    }

}
